<?php

/**

 * 会员服务层

 * @author maniac

 */

namespace app\common\service;
use app\common\model\Collection as CollectionModel;
use app\common\model\Columns;
use app\common\model\Goods as GoodsModel;
use app\common\model\Stores;
use think\facade\Log As Log;
use app\facade\Aes AS AesFacade;
use app\common\model\Verify AS VerifyModel;
use app\common\model\Members AS MembersModel;
use app\common\model\MemberData AS MemberDataModel;
use app\common\model\MemberPoints AS MemberPointsModel;
use app\common\model\MemberBalance as MemberBalanceModel;
use app\common\model\OrderGoods as OrderGoodsModel;
use app\common\model\RechargeConfig as RechargeConfigModel;
use app\common\model\MemberRecharge as MemberRechargeModel;
use app\common\model\MembersMessage as MembersMessageModel;

use app\common\model\Invoice as InvoiceModel;

use app\common\model\Orders AS OrdersModel;

use app\common\model\MemberList AS MemberListModel;

use app\facade\Options AS OptionsFacade;

use app\facade\Salesmans;
use app\common\model\OrderBank AS OrderBankModel;

use app\common\model\MemberCash AS MemberCashModel;
use app\common\model\MemberYongjin AS MemberYongjinModel;
use app\facade\Distribution;
use app\facade\Orders;

class Members extends Base

{

	/**
	 * 获取管理员管理的栏目
	 * @param int $userid 管理员 id
	 */
	public function getAdminColumns($userid)
	{
		$info = MembersModel::field('role_id,admin_columns')->where('id', $userid)->find();
		if ($info['role_id'] == 1) {
			// 超级管理员管理所有栏目
			$where = [];
		} elseif ($info['admin_columns']) {
			// 其他管理员按管理栏目权限划分
			$where[] = [
				['id', 'in', $info['admin_columns']],
			];
		} else {
			// 没有管理栏目无法查看信息分类树
			return false;
		}
		$data = Columns::field('id,parent_id,name,is_last')->where($where)->order('id ASC')->select();
		return $data;
	}

	/**
	
	* 会员注册
	
	* @param int $mobile 注册手机号
	
	* @param int $password 密码
	
	* @param int $verify 验证码
	
	*/
	
	public function add($data)
	
	{
		$wheres = [
		
			'mobile' => $data['mobile'],
			
			'code' => $data['verify'],
			
			'type' => 1,
		
		];
		
		$verify = VerifyModel::field(true)->where($wheres)->find();
		
		$code = $verify['code'];
		
//		if (empty($verify)|| $code != $data['verify'] && $data['verify'] != '1234') {
//
//			exception('验证码错误，请重新输入');
//
//		}
		
		$where = [
		
			'mobile' => $data['mobile'],
		
		];
	
		$member = MembersModel::field('id,mobile,password')->where($where)->find();
		if (!empty($member)) {
			
			exception('当前手机号已注册');
			
		}else{
			
			$salesman_id = isset( $data['salesman_id'] )?$data['salesman_id']:0;

			$parent_id = isset( $data['parent_id'] )?$data['parent_id']:0;

			$password = AesFacade::encrypt($data['password']);
			if($parent_id){
                $parent = MembersModel::field('id')->where('referral_code',$parent_id)->find();//判断推荐码是否有效
                if(!$parent){
                    exception('推荐码无效，请重新输入');
                }
                $parent_id = $parent['id'];//上级ID
            }
			
			$members =  MembersModel::create([

				'parent_id'  => 0,

				'role_id'   => 1,

				'salesman_id'   => $salesman_id,

				'mobile'  => $data['mobile'],

				'username'  => $data['mobile'],

				'password'  => $password,

				'status'    => 1,

			]);
			if ($members->id) {


				if ( $salesman_id > 0 ) {

					$options = unserialize(OptionsFacade::option('shop_info'));
					
					$balance = $options['extension_user'];
					
					$remark = '推广用户注册佣金';
					
					Salesmans::record($salesman_id,$balance,$remark,0,0);
					
				}

				if($parent_id > 0){
				    Distribution::can_offline($members->id,$parent_id);//判断是否可成为下线
                }
                Distribution::is_distribution($members->id);//判断是否可成为分销商
				
				$userid = $members->id;
			
				// 会员副表
			
				MemberDataModel::create([
			
					'id'              => $userid,
			
					'login_nums'      => 1,
			
					'last_login_ip'   => request()->ip(),
			
					'last_login_time' => time(),
			
				]);
			
				$encrypt = [
			
					'id'      => $userid,
				
					'mobile' => $data['mobile'],
				
					'password'  => AesFacade::encrypt($data['password']),
				
				];
				
				$userToken = AesFacade::encrypt(http_build_query($encrypt));
				
			} else {
			
				exception('添加会员失败');
			
			}		
			
		}
		
		$info                = $this->info($userid);
		
		$info['userToken']   = $userToken;
		
// 		Log::write($info,'info');
		
		return $info;
	
	}

	/**
	 * 绑定手机号
	 */
	public function bindMobile($data){

//        $wheres = [
//            'mobile' => $data['mobile'],
//            'code' => $data['verify'],
//        ];
//        $verify = VerifyModel::field(true)->where($wheres)->find();
//
//        $code = $verify['code'];
//        if (empty($verify) || $code != $data['verify']) {
//            exception('验证码错误，请重新输入');
//        }

		$where = [
			'mobile' => $data['mobile'],
		];
		$member = MembersModel::field('id,wechat_id,mobile,password,nickname,rmd_code')->where($where)->find();
		if (!$member) {
			exception('请先注册手机号哟！');
		}

		$w_where=[
			['member_id','eq',$member['id']],
			['openid','eq',$data['openid']]
		];
		$w_count=WechatUsersModel::where($w_where)->count("*");
		if($w_count){
			exception('手机号已经绑定哟！');
		}


		$wu_where=[
			'openid'=>$data['openid'],
		];
		$res=(new WechatUsersModel())->where($wu_where)->update(['member_id' => $member['id']]);

		if($res){
			$encrypt = [
				'id' => $member['id'],
				'mobile' => $member['mobile'],
				'password' => $member['password'],
			];
			$result['userToken'] = AesFacade::encrypt(http_build_query($encrypt));
			return $result;
		}

		exception('绑定失败哟');
	}


	/**
	 
	 * 登录
	  
	 * @param int $mobile 注册手机号
	
	 * @param int $password 密码
	   
	 */
	public function login($data)
	
	{
		$where = [
			
			'mobile' => $data['mobile'],
			
			'status' => 1,
			
		];
		$info = MembersModel::field('id,parent_id,mobile,password,points,balance')->where($where)->find();
		
		if (!empty($info)) {
			
			$info = $info ? $info->toArray() : [];
			
			$password = AesFacade::encrypt($data['password']);
			
			if ($password == $info['password']) {
				
				$encrypt = [
				
					'id'      => $info['id'],
					
					'mobile' => $info['mobile'],
					
					'password'  => $info['password'],
					
				];
					
				$userToken = AesFacade::encrypt(http_build_query($encrypt));
					
				$info['userToken']   = $userToken;
				
				return $info;
			}
			
			exception('密码错误，请重新输入');
			
		}
		
		exception('您的手机号并未注册，请先注册');
		
	}
	/**
	
	* 修改密码
	 
	* @param int $mobile 手机号
	
	* @param int $password 新密码
	
	*/
	public function password($data)
	
	{
		$wheres = [
		
			'mobile' => $data['mobile'],
			
			'code' => $data['verify'],
			
			'type' => 2,
		
		];
		
		$verify = VerifyModel::field(true)->where($wheres)->find();
		
		$code = $verify['code'];
		
		if (empty($verify)|| $code != $data['verify']) {
				
			exception('验证码错误，请重新输入');
				
		}
		$where = [
			
			'mobile' => $data['mobile'],
			
		];
		
		$info = MembersModel::field('id,parent_id,username,mobile,password,points,balance')->where($where)->find();
		if(empty($info)){
			
			exception('当前手机号不是平台用户，请注册。');
			
		}
		
		$password = AesFacade::encrypt($data['password']);
		
		if ($info['password'] == $password) {
			
			exception('新密码与原密码相同，请直接登录。');
			
		}else{
			
			$info->password = $password;
			
			$info -> save();
		}
	
		return true;
	
	}
    /**

     * 获取会员信息

     * @param int $wechatId 微信用户 id

     */

    public function info($where)
    {
        return MembersModel::field(true)->append(['distribution_status'])->where('id',$where)->find();

    }

    /**
    
    * 完善资料
    
    * @param int $userId 用户 id
    
    * @param object $post 用户信息 
    
    */
    
    public function editInfo($post,$userId)
    
    {
    	
    	$info = MembersModel::field('id,parent_id,password,nickname,image_uri,points,balance')->where('id', $userId)->find();
    	
    	$info->nickname = $post['nickname'];
    	
    	$info->image_uri = $post['image_uri'];
    	
    	if($info->save()){
    		
    		return true;
    		
    	}
    	
    	return false;
    
    }

    /**
    
    * 修改密码
    
    * @param int $userId 用户 id
    
    * @param object $post 用户信息
    
    */
    
    public function editPassword($post,$userId)
    
    {
    	$old_password = AesFacade::encrypt($post['old_password']);
    	
    	$password = AesFacade::encrypt($post['password']);
    	if ($old_password == $password) {
    		exception('原密码与新密码相同，请重新输入。');
    	}
    	$info = MembersModel::field('id,password')->where('id', $userId)->find();

    	if ($info['password'] == $old_password) {
    		
    		$info->password = $password;
    		
    		if($info->save()){
    		
    			return true;
    		
    		}
    	}
    	 
    	exception('原密码错误，请重新输入。');
    
    }
    /**

     * 积分变动记录

     * @param int    $userId 用户 id

     * @param string $limit  分页条件

     * @param int    $status

     */

    public function pointsRecords($userId, $limit, $type)

    {
    
        $member = MembersModel::field('points')->where('id', $userId)->find();

        $where[]  = [

            ['userid', 'eq', $userId],

        ];

        if($type == 1){
           $wheres[] = [
               ['points','like','%-%']
           ];
        }else{
            $wheres[] = [
                ['points','>',0]
            ];
        }
        return [

            'points' => $member['points'],
            
            'num' => MemberPointsModel::field(true)->where($where)->where($wheres)->count(),

            'list'   => MemberPointsModel::field(true)->where($where)->where($wheres)->order('id DESC')->limit($limit)->select(),

        ];

    }

   
    
    /**
     
     * 我的余额明细
     
     * @param int $uid  用户编号
     
     * @param string $limit  分页条件
     
     */
    public function balance($uid, $limit,$type)
    {
        $where = [];
        if($type >0){
            $where['type'] = $type;
        }
    	
        $info = MemberBalanceModel::field(true)
            ->where('userid', $uid)
            ->where($where)
            ->order('id desc')
            ->limit($limit)
            ->select()->toArray();
        return $info;
    }

	/*
	 * 余额金额列表
	 * @author 董伟
	 * */
	public function rechargeConfig(){
		$list=RechargeConfigModel::field(true)->select()->toArray();
		return $list;
	}

	/*
	 * 获取信息
	 * @author 董伟
	 * */
	public function getConfig($id){
		$info=RechargeConfigModel::field(true)->where('id',$id)->find();
		return $info;
	}

	/*
	 * 创建订单
	 *
	 * @author 董伟
	 * */

	public function createRechargeOrder($arg){

		$data['cz_type']=$arg['cz_type'];
		$data['cz_code']=Orders::order_no('RCH',$arg['cz_uid']);
		$data['cz_uid']=$arg['cz_uid'];
		$data['cz_amount']=$arg['cz_amount'];
		$data['cz_points']=$arg['cz_points'];
		$data['cz_add_time']=time();
		$data['cz_pay_status']=0;
		$data['cz_pay_code']='';

		$order = MemberRechargeModel::create($data);

        $bank['tableflag'] = 'member_recharge';
        $bank['bankpostid'] = $data['cz_code'];
        $bank['pid'] = $order->id;
        $bank['pay_amount'] = $data['cz_amount'] ;
        $bank['pay_type'] = $arg['pay_type'] ;
        $bank['create_time'] = time() ;
        $bank['uid'] = $data['cz_uid'] ;
        $orders = OrderBankModel::create($bank);
        if ($orders->id) {
            $datas['id'] = $data['cz_code'];
        }
		return $datas;
	}


	/*统计子节点的id*/
	function getSubs($categorys,$catId=0,$level=1){
		$subs=array();
		foreach($categorys as $item){
			if($item['parent_id']==$catId){
				$item['level']=$level;
				$subs[]=$item['id'];
				$subs=array_merge($subs,$this->getSubs($categorys,$item['id'],$level+1));
			}
		}
		return $subs;
	}



   
    
    /**
    
    * 发票申请
    
    * @param int $userId 用户 id
    
    * @param object $post 用户信息
    
    */
    
    public function invoice($post)
    
    {
    	
    	$where = [
    
    		'id'  => $post['userid'],
    	
    	];
    	
    	$member = MembersModel::field('id,price')->where($where)->find();
    	
    	if ($post['money'] > $member['price']) {
    		
    		exception('对不起，您选择的开票金额超出您的购物金额。');
    		
    	}
    	
    	$invoice =  InvoiceModel::create([

				'userid'  => $post['userid'],

				'invoice_type'   => $post['invoice_type'],

				'sort'  => $post['sort'],

				'title'  => $post['title'],

				'phone'  => $post['phone'],

				'address'  =>isset($post['address'])?$post['address']:'',

				'itin'  => isset($post['itin'])?$post['itin']:'',

				'bank'  => isset($post['bank'])?$post['bank']:'',

				'card_num'  =>  isset($post['card_num'])?$post['card_num']:'',

				'money'    => $post['money'],

				'status'    => 0,

			]);
    	
    	if ($invoice->id) {
    		
    		$member->price = $member['price'] - $post['money'];
    		
    		$member->save();
    		
    		return true;
    		
    	}else{
    		
    		return false;
    		
    	}
    
    }
    
    /**
     * 
     * 充值
     * @param unknown $uid
     * @param unknown $price
     * @return unknown
     */
    
    public function recharge($uid,$price)
    {
    	$member = MembersModel::field('id,balance,nickname')->where('id',$uid)->find();   	 
    	$data['type']               = 3; //订单类型 1-商城订单 2-书城订单 3-充值
    	$data['out_trade_no']       = unid();
    	$data['order_no']           = time().mt_rand(100000, 999999);
    	$data['userid']       		= $member['id'];
    	$data['username']       	= $member['nickname'];
    	$data['order_amount']       = $price;
    	$data['pay_amount']         = $price;
    	$order                      = OrdersModel::create($data);
    	if ($order->id) {
    
    		$datas['id'] = $order->id;
    
    		$datas['order_amount'] = $price;
    
    	}
    	return $datas;
    
    }
    
    /**
    
    * 修改会员余额（积分|金币）
    
    * @param  array $data 请求的信息
    
    */
    
    public function balanceChange($data)
    
    {
    
    	$id    = (int)$data['id'];
    
    	$key   = $data['key'];
    
    	$value = $data['value'];
    
    	$remark = isset($data['remark'])?$data['remark']:'管理员后台修改';
    
    	$member = MembersModel::field('id,wechat_id,'.$key)->where('id', $id)->find();
    
    	if (!$member) {
    
    		exception('会员不存在');
    
    	}
    
    	$member->$key = ['inc', $value];
    
    	if ($member->save()) {
    
    		$model = '\app\common\model\Member'.ucfirst($key);
    
    		$model::create([
    
    				'userid'    => $id,
    
    				$key        => $value,
    
    				'remark'    => $remark,
    
    				'surplus'    => $data['surplus'],
    
    				'sort'    => $data['sort'],
    
    				]);
    
    		return (int)$member->$key + $value;
    
    	}
    
    	exception('修改失败');
    
    }
    
    /**
    
    * 订单完成赠送积分和金币
    
    * @param  string $userid 用户编号
    
    * @param  string $order_id 订单编号
    
    * @param  string $type 订单类型 1-商品订单 2-商品券订单
    
    */
    
    public function MemberChange($userid,$order_id,$type)
    
    {
    	
    	$member = MembersModel::field('id,salesman_id,points')->where('id',$userid)->find(); 
    		
    	$where = [
    		
    		'order_id'=>$order_id,
    		
    	];
    	
    	$goods = OrderGoodsModel::field('goods_id,shop_id,give_points,sale_price,goods_nums')->where($where)->select()->toArray();
    		
    	foreach ($goods as $key =>$val){
    		//Log::write($member['salesman_id'],'info'); 
    		if ($member['salesman_id'] > 0 ) {

    			$options = unserialize(OptionsFacade::option('shop_info'));
    			
    			if ($val['shop_id'] == 1) {

    				//Log::write($options,'info');
    				$balance = $options['royalty_zy']*$val['sale_price']*$val['goods_nums']/100;
    				//Log::write($balance,'info'); 
    				$remark = '推广用户购买自营商品提成';
    				
    				Salesmans::record($member['salesman_id'],$balance,$remark,$val['shop_id'],$order_id);
    				 
    			}else{
    				
    				$balance = $options['royalty_fzy']*$val['sale_price']*$val['goods_nums']/100;
    				
    				$remark = '推广用户购买非自营商品提成';
    				
    				Salesmans::record($member['salesman_id'],$balance,$remark,$val['shop_id'],$order_id);
    				 
    			}
    			 
    		
    			
    				
    		}
    		
    		$where = [
    			 
	    		'navs_id' => $type,
	    			 
	    		'userid' => $userid,
	    			 
	    		'goods_id' => $val['goods_id'],
    			 
    		];
    			
    		$memberlist = MemberListModel::field('id,buynum')->where($where)->find();
    		
    		if (empty($memberlist)) {
    			
    			$mem = MemberListModel::create([
    			
    				'userid' => $userid,
    				
    				'navs_id' => $type,
    				
    				'goods_id' => $val['goods_id'],
    				
    				'buynum' => 1,
    				
    				'buy_last_time' => time(),
    			
    			]);
    			
    		}else{
    			$memberlist->buynum = ['inc', 1];
    			
    			$memberlist->save();
    		}
    			
    				
    		if ($val['give_points'] > 0) {
    			    		
    			$data = [
	    		
	    			'id'=>$userid,
	    				 
	    			'key'=>'points',
	    				 
	   				'value'=>$val['give_points'],
	    				 
	    			'remark'=>'购物赠送积分',
	    			
	    			'surplus'        => $member['points']+$val['give_points'],
	    			 
	    			'sort'        => 1,
    		
    			];
    			$this -> balanceChange($data);
    	
    		}
	
    	}
    
    }

    /*
     * 添加消息
     *
     *$userId   int     用户ID
     *$content   content     内容
     * */
    public function add_messge($userId,$content){

        $in = [
            'userid'=>$userId,
            'content'=>$content,
            'create_time'=>time(),
            'read_status'=>0,
        ];
        $mm = new MembersMessageModel();
        $mm->save($in);
        return;
    }
    /**

     * 用户消息

     * @param int $uid  用户编号

     * @param string $limit  分页条件

     */
    public function messagelist($uid, $limit)
    {

        $info = MembersMessageModel::field(true)
            ->where('userid', $uid)
            ->order('id desc')
            ->limit($limit)
            ->select()->toArray();
        return $info;
    }

    /*
     * 修改/绑定手机号
     *
     * $userId      int       用户ID
     * $moblie      int       手机号
     * */
    public function editMobile($userId,$mobile)
    {

        $where = [
            'mobile' => $mobile,
        ];

        $member = MembersModel::field('id')->where($where)->find();
        if ($member) {
            exception('该手机号已被绑定过');
        }
        $info = MembersModel::field('id,mobile')->where('id',$userId)->find();
        $info->mobile = $mobile;
        $info->save();
        return 1;
    }
	/*
	 * 添加关注/收藏
	 *
	 * $userId      int     用户ID
	 * $data        int     收藏数据
	 * */
	public function add_collection($userId, $data)
	{
		if (!$data['data_id']) {
			exception('data_id不能为空');
		}
		$data['data_type'] = $data['data_type'] ? $data['data_type'] : 'product';
		$where = [
			['userid', 'eq', $userId],
			['data_id', 'eq', $data['data_id']],
			['data_type', 'eq', $data['data_type']],//商品product视频video论文paper分享share资料content
		];
		$col = CollectionModel::field('id')->where($where)->find();
		if ($col) {//判断是否收藏过 如果是取消收藏
			CollectionModel::destroy($col['id'], true);//取消收藏
			return 1;
		} else {
			$data['userid'] = $userId;

			$info = CollectionModel::create($data);//收藏
			if ($info) {
				return 1;
			}
		}
		return false;

	}

	/*
	 * 收藏记录
	 *
	 * $userId      int     用户ID
	 * $type        int     类型      商品product商户shop
	 * */
	public function collection_list($userId, $type, $page = 0, $limit = 0)
	{
		$where = [];//条件
		$addend = [];//追加字段
		$order = 'id';//排序
		$where = [
			['userid', 'eq', $userId],
			['data_type', 'eq', $type]
		];
		switch ($type) {
			case 0:
				$addend = ['goods'];
				break;
			case 1:
				$addend = ['shop'];
				break;
		}
		$col_mod = new CollectionModel();
		$list = $col_mod->getList($where, '', $order, $addend, $page, $limit);
		return $list;
	}
	/**
	 * 移除
	 * @param int $id 收藏商品表主键
	 */
	public function deleteCollect($id)
	{
		if (!$id) {
			exception('请选择要移除的商品');
		}
		$id = explode(',',$id);
		foreach ($id as $k =>$v){
			$info = CollectionModel::field('id,data_id,data_type')->where('id', $v)->find();
			if (!$info) {
				exception('收藏的商品不存在');
			}

			if($info['data_type']=='product'){
				$goods=Stores::field('id,collect_nums')->where('id',$info['data_id'])->find();
			}else{
				$goods = GoodsModel::field('id,collect_nums')->where('id', $info['data_id'])->find();
			}
			if ($info) {
				CollectionModel::destroy($v);
				if($info['type']==1){
					$goods->collect_nums = ['dec', 1];
					$goods->save();
				}else{
					$goods->collect_nums = ['dec', 1];
					$goods->save();
				}
			}
		}
		return 1;

	}
}

